package com.lazyfish.scss.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lazyfish.scss.bean.Course;
import com.lazyfish.scss.bean.User;
import com.lazyfish.scss.dao.CourseDAO;
import com.lazyfish.scss.util.ValidateJson;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/SelectCourseServlet")
public class SelectCourseServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Map<String,String> map=new HashMap<String,String>();
        boolean flag=true;
        User user=new User();//用于获取seesion信息
        user = (User)request.getSession().getAttribute("user2");
        if(user==null){
            flag=false;
            map.put("status", "-1");
            map.put("msg", "未登录。");
        }
        JSONObject json;
        if(flag){
            json = ValidateJson.verification(request, "list");
            JSONArray ja=json.getJSONArray("list");
            for (int i = 0; i <ja.size(); i++) {
                System.out.println(ja.get(i));
                new CourseDAO().selectCourses(user.getId(), Integer.parseInt(""+ja.get(i)));
            }
            //输出json格式的map
            map.put("status", "200");
            map.put("msg", "选课成功！由于选课火爆将不能退选！");
            PrintWriter out = response.getWriter();
            String ListUserJson = JSON.toJSONString(map);
            out.write(ListUserJson);
        }else{
            //输出json格式的map
            PrintWriter out = response.getWriter();
            String ListUserJson = JSON.toJSONString(map);
            out.write(ListUserJson);
        }
    }
}
